import { getUserDetailById, getUserInfo, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },

    // 将获取到的用户信息传递给state
    setUserInfo(state, res) {
      state.userInfo = res
    },

    // 退出功能
    removeUserInfo(state) {
      state.userInfo = {}
      state.token = ''
      removeToken()
    }
  },
  actions: {
    // 获取登录token
    async fetchLogin(context, data) {
      // 将值传给data
      const res = await login(data)
      // 调用setToken将将值传过去
      context.commit('setToken', res)
    },

    // 获取用户信息
    async fetchUserInfo(context) {
      // 获取用户信息
      const res = await getUserInfo()

      // 获取用户头像
      const detailRes = await getUserDetailById(res.userId)

      context.commit('setUserInfo', { ...res, ...detailRes })
    }
  }
}
